package jou.cs.service.impl;

import jou.cs.configurator.CONST;
import jou.cs.entity.TAns;
import jou.cs.entity.TQus;
import jou.cs.mapper.AnsRepository;
import jou.cs.mapper.PlaceRepository;
import jou.cs.mapper.QusRepository;
import jou.cs.service.QuestionService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class Question implements QuestionService {
    @Resource
    QusRepository qusRepository;
    @Resource
    AnsRepository ansRepository;
    @Resource
    PlaceRepository placeRepository;

    @Override
    public void addQuestion(TQus question) {
        qusRepository.save(question);
    }

    @Override
    public void deleteQuestion(Long qid) {
        qusRepository.deleteById(qid);
    }

    @Override
    public void updateQuestion(TQus question) {
        qusRepository.save(question);
    }

    @Override
    public TQus getQuestionById(Long qid) {
        return qusRepository.findById(qid).orElse(null);
    }

    @Override
    public Page<TQus> getQuestionByPage(int page) {
        return qusRepository.findAll(PageRequest.of(page, CONST.PAGE_SIZE));
    }

    @Override
    public List<Map<Object, Object>> getQuestionByUserId(Long uid) {
        return qusRepository.findAllByUid(uid).stream().collect(ArrayList::new, (list, qus) -> {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("qus", qus);
            map.put("pls", placeRepository.findById(qus.getPid()));
            list.add(map);
        }, ArrayList::addAll);
    }

    @Override
    public Page<TQus> getQuestionByUserIdAndPage(Long uid, int page) {
        return qusRepository.findAllByUid(uid, PageRequest.of(page, CONST.PAGE_SIZE));
    }

    @Override
    public void addAnswer(Long qusId, TAns ans) {
        ans.setQid(qusId);
        ansRepository.save(ans);
    }

    @Override
    public List<TAns> getAnsByQusId(Long qusId) {
        return ansRepository.findAllByQid(qusId);
    }

    @Override
    public Page<TAns> getAnsByQusIdAndPage(Long qusId, int page) {
        return ansRepository.findAllByQid(qusId, PageRequest.of(page, CONST.PAGE_SIZE));
    }

    @Override
    public void deleteAns(Long id) {
        ansRepository.deleteById(id);
    }

    @Override
    public List<Map<Object, Object>> getQusByPid(Long pid) {
        return qusRepository.findAllByPid(pid).stream()
                .map(qus -> {
                    Map<Object, Object> map = new HashMap<>();
                    map.put("id", qus.getId());
                    map.put("title", qus.getTitle());
                    map.put("count",ansRepository.findAllByQid(qus.getId()).size());
                    return map;
                }).collect(Collectors.toList());
    }
}
